package ub.pis.net;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;

import ub.pis.Canco;
/**
 * Clase handler para extraer la informacion del xml "top de canciones" de un artista.
 * @author nagash
 *
 */
public class TopSongsXMLHandler extends DefaultHandler {
	private Canco cancoActual;
	private List<Canco> topSongs;
	private StringBuilder sbTexto;
	private boolean large_img;
	private boolean track_name;

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);

		if (this.cancoActual != null)
			sbTexto.append(ch, start, length);
	}

	public void startDocument() throws SAXException {

		super.startDocument();

		topSongs = new ArrayList<Canco>();
		sbTexto = new StringBuilder();
	}

	/**
	 * setea los booleanos large_img i track_name. Si encuentra una etiqueta "track"
	 * track_name = true, si encuentra una etiqueta "image" con atributo "extralarge"
	 * large_img = true.
	 */
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {

		super.startElement(uri, localName, name, attributes);

		if (localName.equals("track")) {
			cancoActual = new Canco();
			large_img = false;
			track_name = true;
		} else if (localName.equals("image")
				&& ((attributes.getValue("size").equals("extralarge")))) {
			large_img = true;
		}
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {

		super.endElement(uri, localName, name);

		if (this.cancoActual != null) {

			if (localName.equals("name") && track_name) {
				cancoActual.setTitol(sbTexto.toString().trim());
				track_name = false;
			} else if (localName.equals("image") && large_img) {
				cancoActual.setCaratula(sbTexto.toString().trim());
				large_img = false;
			} else if (localName.equals("track")) {
				topSongs.add(cancoActual);
			}

			sbTexto.setLength(0);
		}
	}

	/**
	 * retorna la lista con el top de canciones del artista.
	 * @return List<Canco>
	 */
	public List<Canco> getTopSongs() {
		return topSongs;
	}

}
